<template>
  <el-card class="box-card">
    <div>
      <el-button type="primary" icon="el-icon-plus" style="margin-bottom: 20px;" @click="showDialog">添加</el-button>
    </div>
    <!-- 表单 -->
    <el-card>
      <el-table :data="tradmark" border style="width: 100%">
        <el-table-column type="index" width="80" align="center" label="序号">
        </el-table-column>
        <el-table-column prop="tmName" label="品牌名称" width="320">
        </el-table-column>
        <el-table-column label="品牌LOGO" width="320">
          <template v-slot="scoped">
            <el-image style="width: 150px; height:80px" :src="scoped.row.logoUrl"></el-image>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template v-slot="{ row }">
            <el-tooltip class="box-item" effect="dark" content="修改" placement="top">
              <el-button type="warning" icon="el-icon-edit-outline" size="small" @click="toEditTradmark(row)"></el-button>
            </el-tooltip>
            <el-tooltip class="box-item" effect="dark" content="删除" placement="top">
              <el-button type="danger" icon="el-icon-delete" size="small" @click="toDeleTradmark(row.id)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>

      </el-table>
    </el-card>
    <!-- 分页 -->
    <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[3, 5, 10, 20]"
      layout="prev, pager, next, jumper,->,sizes,total" :total="total" @size-change="handleSizeChange"
      @current-change="handleCurrentChange" />

    <!-- 弹出框 -->
    <el-dialog :title="`${initInfo.id ? '修改' : '添加'}品牌`" :visible.sync="dialogVisible" width="50%">
      <el-form style="width: 80%" label-width="120px" :model="initInfo" ref="initInfo" :rules="trademarkRules" >
        <el-form-item label="品牌名称：" prop="tmName">
          <el-input v-model="initInfo.tmName" type="text"></el-input>
        </el-form-item>
        <el-form-item label="品牌LOGO:" prop="logoUrl ">
          <el-upload class="avatar-uploader" action="http://gmall-h5-api.atguigu.cn/admin/product/fileUpload"
            :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
            <img v-if="imageUrl" :src="imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>

      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="btnTrademark(initInfo)">确 定</el-button>
      </span>
    </el-dialog>
  </el-card>
</template>
<script>

import { reqGetTradmarkList, SaveTradmarkList, DeleteTrademarkInfo, UpdataTradmark } from '@/api/Tradmark'
import { Message, MessageBox } from 'element-ui';

export default {
  name: 'Tradmark',
  data() {
    return {
      // 点击弹出添加或者更新框
      dialogVisible: false,
      // 分页列表
      tradmark: [],
      // 分页器
      currentPage: 1,
      pageSize: 3,
      total: 0,
      // 上传图片数据
      initInfo: {
        tmName: '',
        logoUrl: '',
      },
      imageUrl: '',
      // tradmarkRef: {}
      trademarkRules: {
        tmName: [
          { required: true, message: '请输入品牌名称', trigger: 'blur' },
          { min: 1, max: 6, message: '品牌名称应该是在1到6之间', trigger: 'blur' }
        ],
        logoUrl: [
          {
            required: true,
            message: '请上传一张图片',
            trigger: 'change'
          }
        ]
      }
    };

  },
  methods: {

    // 分页器
    //一页几条时触发
    handleSizeChange(val) {
      this.pageSize = val
      this.currentPage = 1
      this.getTradmark(this.currentPage, this.pageSize)
    },
    // 当前页改变时触发
    handleCurrentChange(val) {
      this.currentPage = val
      this.getTradmark(this.currentPage, this.pageSize)
    },
    // 发送请求获取分页数据
    async getTradmark(page, limit) {
      const result = await reqGetTradmarkList(page, limit)
      // console.log(result)
      if (result.code === 200) {
        this.tradmark = result.data.records
        this.total = result.data.total;
      }
    },

    // 点击添加显示弹框
    showDialog() {
      // 清空校验规则
      // this.tradmarkRef.clearValidate()
      // 删除原对象中的值
      delete this.initInfo.id
      // 清空原对象中的值
      Object.assign(this.initInfo)
      this.imageUrl = ''
      this.initInfo.tmName = ""
      this.dialogVisible = true

    },
    // 上传图片
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
      this.imageUrl = res.data
      this.initInfo.logoUrl = res.data

    },
    // 图片上传之前的校验
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    // 图片上传成功之后的链接地址


    // 添加图片
    // async addTrad(initInfo) {
    //   const result = await SaveTradmarkList(initInfo)
    //   // console.log('aaaa',result)
    //   if (result.code === 200) {
    //     // 关闭添加窗口
    //     this.dialogVisible = false
    //     // 重新发送请求获取分页列表数据
    //     this.getTradmark(this.currentPage, this.pageSize)

    //     // 清空文本框
    //     // this.initInfo.tmName = ""
    //     // this.initInfo.logoUrl = ""


    //   }
    // },

    // 更新数据的回显
    toEditTradmark(row) {
      this.dialogVisible = true
      Object.assign(this.initInfo, row)
      this.imageUrl = row.logoUrl

    },

    // 删除某条品牌数据
    toDeleTradmark(id) {
      this.$confirm('您真的要删除此商品品牌吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        await DeleteTrademarkInfo(id)
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
        // 重新发送请求获取数据
        this.getTradmark(1, 5)
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    // 判断是更新还是添加数据
     btnTrademark(initInfo) {
      // console.log(initInfo)
     
      if (!initInfo) return
       this.$refs.initInfo.validate(async(valid) => {
        if (valid) {
          // 校验通过后
         if(initInfo.id){
          // 如果有id值 此时说明是更新品牌
           await UpdataTradmark(this.initInfo)
         }else{
          // 没有id值 此时说明是添加操作
          await SaveTradmarkList(this.initInfo)
         }
         this.$message.success(`${initInfo.id ? '更新' : '添加'}品牌成功了...`);
         this.getTradmark(this.currentPage, this.pageSize)

        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    resetForm(initInfo) {
      this.$refs.initInfo.resetFields();
    }
  },

  mounted() {
    this.getTradmark(this.currentPage, this.pageSize)
  },

}

</script>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style> 